package usgs.bip.swap.ctl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


 

@SuppressWarnings("serial")
public class SpeciesInformationServlet extends HttpServlet {
	
	 
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		 
		String scientificName = req.getParameter("sname");
		String fileNamePrefix = getServletConfig().getInitParameter("qaqcFileBaseURL");
		String source = req.getParameter("source");
		String output = "";
		
		if(scientificName != null && source != null){
			
			if(source.contains("profile")){
				output = this.formatProfileInfo(scientificName, fileNamePrefix);
			}
			else if(source.contains("natureServe")){
				output = this.formatNatureServeInfo(scientificName);
			}
			
		}

        resp.setContentType("text/plain");
        resp.getWriter().println(output);
		 

	}
	
	private String formatNatureServeInfo(String scientificName) {
		 
 
		String html = "No information available";
		 
		String uid = this.getNatureServeUIDForName(scientificName);
		
		if(uid.length() > 0){
			URL url = null; 
				
			try{
				/* Note that the natureServe stauts is retrieved as html from a php application
				 * hosted at a free web hosting service bytehosting9.com. username b9_9243760 
				 */
				url = new URL("http://www.renderns.byethost9.com/nsfiles/natureServeStatus.php?id=" + uid);		
			}catch(MalformedURLException mue){
				System.err.println(mue); 
			}
	
			if(url == null) {			
				return html;
			}
			
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
				String line = "";
				String newHtml = "";
				while ((line = reader.readLine()) != null) {
					newHtml += line;
		        }
			    if(!newHtml.isEmpty()) {
			    	html = newHtml;
			    }
			    
			}catch(Exception e){
				e.printStackTrace();
				html = "Error retrieving data";
			}
		}
			 
		return html;
		 
	}

	private String getNatureServeUIDForName(String scientificName) {
		
		String uid = "";
		
	 
		Pattern p = Pattern.compile("\\s+");
		Matcher m = p.matcher(scientificName);
		if(m.find()){
			scientificName = m.replaceAll("+");
	
		}
		String xmlFile = "https://services.natureserve.org/idd/rest/ns/v1/globalSpecies/list/nameSearch?NSAccessKeyId=cf9dc944-3c4b-4b16-b899-df4ebf1ded2f&name=" + scientificName;
 
		try {
	
		         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		        
		         // Use the factory to create a builder
		         DocumentBuilder builder = factory.newDocumentBuilder();
		         Document doc = builder.parse(xmlFile);
		         
		         // Get a list of all elements in the document
		         NodeList list = doc.getElementsByTagName("speciesSearchResult");
		         
		         if(list.getLength() > 0){
		        	 Element element = (Element)list.item(0);
			         uid = element.getAttribute("uid"); 
		         }
  
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return uid;
	}


	private String formatProfileInfo(String scientificName, String fileNamePrefix){
		
		
		String output = "";
		 
		ServletContext context = getServletContext();
		ArrayList<String> stateList = new ArrayList<String>();
		
        if (scientificName != null) {
                
        	String filename = "/data/states.input.txt";
        	
    		//
    		// First get the file InputStream using ServletContext.getResourceAsStream()
    		// method.
    		//
        	java.io.InputStream is = context.getResourceAsStream(filename);
    		if (is != null) {
    			
    			InputStreamReader isr = new InputStreamReader(is);
    			BufferedReader reader = new BufferedReader(isr);
    			String line = "";
    			
    			//
    			// We read the file line by line and later will be displayed on the 
    			// browser page.
    			//
    	 
    			try {
					while ((line = reader.readLine()) != null) {
						String[] strlist = line.split("\t");
						int n = strlist.length;
						
						if(n > 0){
							String state = strlist[0];
							state = state.replaceAll("/\n|\r|\t/", "");
							state = state.trim().toLowerCase();
							if(state != null && !state.equalsIgnoreCase("null")){
								stateList.add(state);
							}
						}
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			
    			if(stateList.size() > 0){    				
    				output = this.formatProfileOutput(scientificName, stateList, fileNamePrefix);
    			}
    		}
    	}
        
        return output;
	}
	
	private String formatProfileOutput(String scientificName, ArrayList<String> stateList, String fileNamePrefix){
	
		
		String filename = fileNamePrefix + "MasterSGCN_Species_QAQC_List.txt";
    	String output = "";
    
		//
		// First get the file InputStream using ServletContext.getResourceAsStream()
		// method.
		//
		URL url = null; 
		
		try{
			/* Note that the natureServe stauts is retrieved as html from a php application
			 * hosted at a free web hosting service bytehosting9.com. username b9_9243760 
			 */
			url = new URL(filename);		
		}catch(MalformedURLException mue){
			System.err.println(mue); 
		}

		if(url == null) {			
			return output;
		}
		
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
			String line = "";
 
		 
				 
				while ((line = reader.readLine()) != null) {
			
					 if(line.contains(scientificName)){
						 output += "{\"scientificName\":\"" + scientificName + "\"";
						 String[] strlist = line.split("\t");
						 int n = strlist.length;
						 for(int i=0; i<n; i++){
								
							 String w = strlist[i];
								
							 switch (i){
									
								 case 1: // vernacular name
											String[] sl = w.split(";");
											int nn = sl.length;
											if(nn > 0){
												output += ", \"vernacularNames\":[";
							  					for(int ii=0; ii<nn; ii++){
							  						output += "\"" + sl[ii] + "\"";
							  						if(ii < nn - 1) {
							  							output += ", ";
							  						}
							  					}
							  					output += "]";
											}
											break;
											
									case 2: // taxonomic category
											 
											break;
											
									case 3: // states
											sl = w.split(";");
											nn = sl.length;
											if(nn > 0){
												output += ", \"states\":[";
							  					for(int ii=0; ii<nn; ii++){
							  						output += "\"" + sl[ii] + "\"";
							  						if(ii < nn - 1) {
							  							output += ", ";
							  						}
							  					}
							  					output += "]";
											}
										break;
										
									
									default:
										break;

								}
						 
						 }
						 output += "}";
						 break; 
					 
					 }
				 
				}
				
		}
		catch(Exception e){
			e.printStackTrace();
		}
		

	
		  return output;
	}
}
